<template>
  <div class="uploadCustomBox">
    <el-upload
        drag
        action
        :auto-upload="false"
        :show-file-list="false"
        accept=".xlsx, .xls"
        :on-change="changeFile">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">只能上传xlsx/xls文件</div>
    </el-upload>
  </div>
</template>

<script>
import utils from '../../../assets/lib/utils'
import xlsx from 'xlsx'
import {addCustom} from "../../../api/api";

export default {
  name: "uploadCustom",
  methods: {
    async changeFile(file) {
      // 获取上传文件
      let fileList = file.raw;
      //文件不存在直接返回
      if (!fileList) return;
      // 添加一个加载动画
      const loading = this.$loading({
        lock: true,
        text: '正在加载，请稍后',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      await utils.delay(500);

      // 将xlsx文件转为二进制文件
      let result = await utils.readFile(fileList);
      // 把转化为二进制的xlsx文件转化为JSON格式
      let weetbook = xlsx.read(result, {type:'binary'});
      weetbook = weetbook.Sheets[weetbook.SheetNames[0]]
      result = xlsx.utils.sheet_to_json(weetbook)
      // 把文件的数据解析为JSON格式数据

      result = utils.formatJSON(result)
      // 逐一把数据上传到服务器

      let index = 0
      let send = () => {
        if (index >= result.length) {
          // 都上传成功l
          loading.close();
          this.$message({
            message: `恭喜你，上传成功,共上传${index}条数据`,
            type: 'success',
            showClose: true,
            onClose: () => {
              this.$router.push('/crm/custom')
            }
          });
          return
        }
        //上传成功和失败
        addCustom(result[index++]).then(data => {
          if (data.code === 0) {
            send()
          } else {
            // 一旦出错，剩下的都不在上传了
            this.$message({
              message: `当前上传第${index}数据出错,已上传${index-1}数据`,
              type: 'warning'
            });
          }
        })
      }
      send();
    }
  },
}
</script>

<style scoped>
.uploadCustomBox {
  display: flex;
  height: 100%;
  justify-content: center;
  align-items: center;
}
</style>